package cn.li.security;

import cn.li.security.entity.Account;
import cn.li.security.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Date;

@SpringBootApplication
@Configuration
public class Application implements ApplicationListener<ContextRefreshedEvent> {


    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }



    @Override
    public void onApplicationEvent(ContextRefreshedEvent ev) {
        //防止重复执行。
        if(ev.getApplicationContext().getParent() == null){
            this.initData();
        }
    }

    @Autowired
    private AccountRepository accountRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
    //配置2个账户， user/123456       admin/12456
    private void initData(){
        Account user = new Account();
        user.setUsername("user");
        user.setCreatedTime(new Date());
        user.setPassword(passwordEncoder.encode("123456"));
        user.addRole("ROLE_user");
        accountRepository.save(user);

        Account admin = new Account();
        admin.setUsername("admin");
        admin.setCreatedTime(new Date());
        admin.setPassword(passwordEncoder.encode("123456"));
        admin.addRole("ROLE_admin");
        accountRepository.save(admin);

    }
}